from PIL import Image, ImageDraw, ImageOps
import pystray
import sys

def create_circular_icon(image_path):
    # 打开原始图片
    original_image = Image.open(image_path).convert("RGBA")
    size = (64, 64)  # 图标大小
    mask = Image.new('L', size, 0)
    draw = ImageDraw.Draw(mask)
    draw.ellipse((0, 0) + size, fill=255)

    output_image = ImageOps.fit(original_image, mask.size, centering=(0.5, 0.5))
    output_image.putalpha(mask)

    return output_image

def on_exit(icon, item):
    icon.stop()

def main():
    icon_path = r"D:\python_gpnu\grade2_1\test\venv\Scripts\p.ico"  # 替换为你的 .ico 图片路径

    try:
        # 尝试打开图标文件以验证路径是否正确
        with open(icon_path, 'rb') as f:
            pass
    except FileNotFoundError:
        print(f"Error: The file {icon_path} does not exist.")
        sys.exit(1)

    circular_icon = create_circular_icon(icon_path)

    menu = (
        pystray.MenuItem(
            'Exit',
            on_exit,
            default=True
        ),
    )

    icon = pystray.Icon(name="CircularIcon", icon=circular_icon, title="Circular Icon App", menu=menu)
    icon.run()

if __name__ == "__main__":
    main()